#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
session 0.1
Cira Rodríguez Brito
conxura at gmail dot com

License:
    Copyright (c) 2012 Cira Rodríguez Brito
    http://www.opensource.org/licenses/mit-license.html

    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or
    sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
'''

from functools import wraps
from google.appengine.api import memcache
import uuid


class Session(dict):
    ''' Session data dictionary.

    Attributes:
        sessionid: Session unique ID, autogenerated
        changed: A boolean indicating if session dictionary has been modified
    '''

    _sessionid = None
    _changed = False

    @property
    def sessionid(self):
        if self._sessionid is None:
            self._sessionid = uuid.uuid4()
        return self._sessionid

    @sessionid.setter
    def sessionid(self, value):
        self._sessionid = value

    @property
    def changed(self):
        return self._changed

    @changed.setter
    def changed(self, value):
        if value:
            self._changed = value

    def __init__(self, sessionid=None, data=()):
        ''' Inits Session class with session ID and data indicated.

        Args:
            sessionid: Session unique ID
            data: Session data
        '''
        dict.__init__(self, data)
        self.sessionid = sessionid

    def __setitem__(self, key, value):
        ''' x.__setitem__(i, y) <==> x[i]=y
        '''
        dict.__setitem__(self, key, value)
        self._changed = True

    def __delitem__(self, key):
        ''' x.__delitem__(y) <==> del x[y]
        '''
        dict.__delitem__(self, key)
        self._changed = True

    @classmethod
    def from_cookie(cls, request):
        ''' Create new session data from cookie and memcache or an empty one
        if not found.

        Args:
            request: webapp2 request object

        Returns:
            Returns a Session instance
        '''
        sessionid = request.cookies.get('sessionid', None)
        if sessionid:
            data = memcache.get('session/%s' % sessionid)
            return Session(
                sessionid,
                data or ()
                )
        return Session()

    def delete_cache(self, request):
        ''' Delete session data using session id from cookies

        Args:
            request: webapp2 request object
        '''
        memcache.delete(self.sessionid)
        request.cookies.delete('sessionid')
        self.sessionid = None

    def write(self, response):
        ''' Save data into session indexed by an id saved in a cookie

        Args:
            response: webapp2 response object
        '''
        if (
            self._changed
            and memcache.set('session/%s' % self.sessionid, dict(self))
            ):
            response.set_cookie('sessionid', str(self.sessionid), path='/')
            self._changed = False


def session(f):
    ''' Decorator for RequestHandler methods to manage web session.

    Session object is given as first parameter.
    '''

    @wraps(f)
    def wrapper(request_handler, *args, **kwargs):
        s = Session.from_cookie(request_handler.request)
        r = f(request_handler, s, *args, **kwargs)
        s.write(request_handler.response)
        return r
    return wrapper
